import cv2
import time,PIL,os
from PIL import ImageGrab
import numpy as np
import time
from tempfile import NamedTemporaryFile
import cv2
from pprint import pprint
from concurrent.futures import ThreadPoolExecutor
 
dataDir = "D:/argostranslate/data"
cacheDir = "D:/argostranslate/cache"
os.environ["XDG_DATA_HOME"] = dataDir
os.environ["XDG_CACHE_HOME"] = cacheDir
import argostranslate.package
import argostranslate.translate
#截图
class ScreenCut:
    def __init__(self):
        if not os.path.exists("E:/ningyuan/sumimoto/Curelasto/tmp/"):
            os.makedirs("E:/ningyuan/sumimoto/Curelasto/tmp/")
        try:
            os.remove("E:/ningyuan/sumimoto/Curelasto/tmp/scr.png")
            os.remove("E:/ningyuan/sumimoto/Curelasto/tmp/cut.png")
        except:pass
        self.scrImg = open("E:/ningyuan/sumimoto/Curelasto/tmp/scr.png","wb+")
        self.cutImg = open("E:/ningyuan/sumimoto/Curelasto/tmp/cut.png","wb+")
        print("111111111111111111111111111111111111111111111")
    def cut(self):
        print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
        self.scrren_cut()
        print("222222222222222222222222222222222222")
        self.img = cv2.imread(self.scrImg.name)
        print("333333333333333333333333333333333333333333")
        cv2.namedWindow('image', cv2.WND_PROP_FULLSCREEN)
        cv2.setWindowProperty('image', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
        cv2.setMouseCallback('image', self.on_mouse)
        print("444444444444444444444444444444")
        cv2.imshow('image', self.img)
        print("555555555555555555555")
        cv2.waitKey(0)
        print("66666666666666666666")
    def scrren_cut(self):
        # img = ImageGrab.grab(bbox=(250, 161, 1141, 610))
        image = ImageGrab.grab()
        image.save(self.scrImg.name)
        # PIL image to OpenCV image
    def on_mouse(self,event, x, y, flags, param):
        self.img2 = self.img.copy()
        if event == cv2.EVENT_LBUTTONDOWN:         #左键点击
            self.point1 = (x,y)
            #cv2.circle(img2, point1, 10, (0,255,0), 5)
            cv2.imshow('image', self.img2)
        elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON):            #按住左键拖曳  
            height,width = self.img2.shape[:2]
            cv2.rectangle(self.img2, self.point1,(x,y),(255,0,0),2)
            
            cv2.imshow('image', self.img2)
        elif event == cv2.EVENT_LBUTTONUP:         #左键释放
            self.point2 = (x,y)
            cv2.rectangle(self.img2, self.point1, self.point2, (0,0,255), 5) 
            cv2.imshow('image', self.img2)
            min_x = min(self.point1[0],self.point2[0])     
            min_y = min(self.point1[1],self.point2[1])
            width = abs(self.point1[0] - self.point2[0])
            height = abs(self.point1[1] - self.point2[1])
            cut_img = self.img[min_y:min_y+height, min_x:min_x+width]
            cv2.imwrite(self.cutImg.name, cut_img)
            cv2.destroyWindow("image")
            self.scrImg.close()
            self.cutImg.close()
            del self.scrImg,self.cutImg,self.point1,self.point2,self.img,self.img2
            print("7777777777777")
            os.remove("E:/ningyuan/sumimoto/Curelasto/tmp/scr.png")
 
class OCR:
    def __init__(self,imagePath,**kwargs):
        print("1111111122222222222")
        from paddleocr import PaddleOCR
        print("ddddddddddddddddddddd")
        # 路径可替换为你的项目文件夹或随便一个专门装PaddleOCR模型的文件夹路径
        self.paddleocr = PaddleOCR(lang='ch', show_log=False, enable_mkldnn=True,
                                   rec_model_dir = ("D:/Paddle-OCR-Models/"
                                                    "ch_ppocr_server_v2.0_rec_infer"),
                                   cls_model_dir = ("D:/Paddle-OCR-Models/"
                                                    "ch_ppocr_mobile_v2.0_cls_infer"),
                                   det_model_dir = ("D:/Paddle-OCR-Models/"
                                                    "ch_ppocr_server_v2.0_det_infer"),
                                   **kwargs
                                   )
        print("eeeeeeeeeeeeeeeeeeeeee")
        self.imagePath = imagePath
        print("3333333333333333333333")
    def ocr(self,**kwargs):
        result = self.paddleocr.ocr(self.imagePath,**kwargs)[0]
        if not result:
            return None
        rd = list(map(lambda i:{"block":{
                                         "topleft":(i[0][0][0],i[0][0][1]),
                                         "topright":(i[0][1][0], i[0][1][1]),
                                         "bottomleft":(i[0][2][0], i[0][2][1]),
                                         "bottomright":(i[0][3][0], i[0][3][1])
                                         },
                                "text":i[1][0],
                                "confidence":i[1][1]},
                      result))
        
        return rd
 
class Translate:
    def __init__(self,
                 fromLang = "en",
                 toLang = "zh",
                 instPack = True):
        if not (os.path.exists(dataDir) and os.path.exists(cacheDir)):
            raise FileNotFoundError("dataDir or cacheDir is not exists")
        if instPack:
            argostranslate.package.update_package_index()
            available_packages = argostranslate.package.get_available_packages()
            package_to_install = next(filter(lambda x: x.from_code == from_code and x.to_code == to_code, available_packages))
            argostranslate.package.install_from_path(package_to_install.download())
        self.fromLang = fromLang
        self.toLang = toLang
    def translate(self,text):
        return argostranslate.translate.translate(text,self.fromLang,self.toLang)
print("aaaaaaaaaaaaaaaaaaaaaaaaaa") 
cut = ScreenCut()
print("bbbbbbbbbbbbbbbbbbbbbbbb")
ocr = OCR("E:/ningyuan/sumimoto/Curelasto/tmp/cut.png",use_mp = True,total_process_num = 4)
print("ccccccccccccccccccccccccccc")
print("Init done.")
 
cut.cut()
print("cut done.")
if not os.path.exists("E:/ningyuan/sumimoto/Curelasto/tmp/cut.png"):
    print("已取消截图")
    exit()
#result = ocr.ocr()
print("ocr done.")
#if not result:
#    print("未识别到文字")
#    exit()
 
ts = Translate("","en","zh",instPack = True)
#for t in map(lambda x:x["text"],result):
    #print(t,"=>",ts.translate(t))